package com.qf.utils;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;

import java.io.InputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

public class DataSourceUtil {
    private static DruidDataSource dataSource;
    private  static ThreadLocal<Connection> threadLocal=new ThreadLocal<Connection>();
    static{
        try {
            Properties properties=new Properties();
            InputStream is = DataSourceUtil.class.getClassLoader().getResourceAsStream("druid.properties");
            properties.load(is);
            is.close();
            dataSource= (DruidDataSource) DruidDataSourceFactory.createDataSource(properties);
        } catch (Exception e) {
            System.out.println("注册驱动失败："+e.getMessage());
        }
    }
    public static DruidDataSource getDataSource(){
        return dataSource;
    }
    public static Connection getConnection(){
        try {
            Connection connection=threadLocal.get();
            if(connection==null){
                connection=dataSource.getConnection();
                threadLocal.set(connection);
            }
            return connection;
        } catch (SQLException e) {
            System.out.println("获取连接失败："+e.getMessage());
        }
        return null;
    }
    public static void closeAll(ResultSet resultSet, Statement statement,Connection connection ){
        try {
            if (resultSet != null) {
                resultSet.close();
            }
            if (statement != null) {
                statement.close();
            }
            if (connection != null) {
                if (connection.getAutoCommit()) {
                    connection.close();
                    threadLocal.remove();
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    public static void begin() throws SQLException {
        Connection connection=getConnection();
        if (connection != null) {
            connection.setAutoCommit(false);
        }
    }
    public static void  commit() throws SQLException {
        Connection connection=getConnection();
        if (connection != null) {
            connection.commit();
        }
    }
    public static void rollback() throws SQLException {
        Connection connection=getConnection();
        if (connection != null) {
            connection.rollback();
        }
    }
    public static void close() throws SQLException {
        Connection connection=getConnection();
        if (connection != null) {
            connection.close();
            threadLocal.remove();
        }
    }
}
